<template>
  <div>
    <el-dialog :title="title" :visible="true" width="80%" @close="handleClose" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="100px">
        <el-form-item label="课程名称：" required>
          <el-input v-model="form.name" placeholder="请输入课程名称" ></el-input>
        </el-form-item>
      </el-form>


      <div class="upload" v-if="showUpload">
        <upload :multiple="false"  @onSuccess="onSuccess"></upload>
        <img :src="form.course_image" v-if="form.course_image" class="icon">
      </div>

      <span slot="footer" class="dialog-footer" v-if="isAdd">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleCommitAdd">确 定</el-button>
      </span>
      <span slot="footer" class="dialog-footer" v-if="isEdit">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleCommitEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Upload from "@/components/Upload";
import { courseInfo } from "@/api/course";
export default {
  components: {
    Upload,
  },
  props:{
    type:{
      type:String
    },
    courseId:{
      type:String|Number
    },
    showUpload:{
      type:Boolean
    }
  },
  computed:{
    isAdd(){
      return this.type === 'add'
    },
    isEdit(){
      return this.type === 'edit'
    },
    title(){
      return this.type === 'add' ? '添加课程' : '编辑课程'
    }
  },
  data() {
    return {
      form: {
        course_image: '',
        name: ''
      }

    }
  },
  created() {
    if(this.isEdit){
      this.getInfo()
    }
  },
  methods: {
    async getInfo(){
      let res = await courseInfo({id:this.courseId});
      this.form.name = res.data.name;
      this.form.course_image = res.data.course_image
    },
    onSuccess(url) {
      this.form.course_image = url[url.length -1]
    },
    handleClose() {
      this.$emit('close')
    },
    handleCommitAdd(){
      if(this.form.name === ''){
        this.$message({
          message: '请填写课程名称！',
          type: 'warning'
        });
        return false;
      }
      if(this.showUpload && this.form.course_image === ''){
        this.$message({
          message: '请填上传图片！',
          type: 'warning'
        });
        return false;
      }
      this.$emit('commitAdd',this.form)
    },
    handleCommitEdit(){
      if(this.form.name === ''){
        this.$message({
          message: '请填写课程名称！',
          type: 'warning'
        });
        return false;
      }
      if(this.showUpload && this.form.course_image === ''){
        this.$message({
          message: '请填上传图片！',
          type: 'warning'
        });
        return false;
      }
      this.$emit('commitEdit',this.form)
    }
  },
}
</script>
<style lang="scss" scoped>
.upload {
  margin-left: 100px;
  .icon{
    width:100px;
    height:100px;
    margin-top:10px
  }
}

</style>
